<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="loadEvendor">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{ prop: 'workNumber', order: 'descending' }">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <!-- sortable 设置排序  向上或者向下 -->
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2,5,8,10,20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 弹层 -->
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
        <addor-edit ref="MySon" @success="hSuccess" @close="showDialog = false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import PageTools from '@/components/PageTools'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import addorEdit from './empDialog'
console.log(EmployeeEnum, 'EmployeeEnum')
const hireType = EmployeeEnum.hireType.reduce((aaa, item) => {
  // 键      值
  aaa[item.id] = item.value
  return aaa
}, {})
export default {
  components: {
    PageTools, addorEdit
  },
  data() {
    return {
      showDialog: false, // 弹层显示隐藏
      list: [], // 员工列表
      page: 1, // 页面值
      size: 2, // 每页条数
      total: 0 // 总数
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 英文转中文
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      console.log(list)
      let header = []
      // header = ['id', 'mobile', 'username', .....]
      // data = [
      //     ['65c2', '1380000002', '管理员', ....],
      //     ['65c3', '1380000003', '孙财', ....],
      // ]
      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })

      // data把list中每一个对象转成 对应的value数组
      data = list.map(obj => {
        // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
        // const key = obj['formOfEmployment'] // 1, 2
        // obj['formOfEmployment'] = hireTypEnmu[key] // hireTypEnmu:{1:'正式', '2':'非正式' }

        return Object.values(obj)
      })

      return { header, data }
    },
    // 导出
    async loadEvendor() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        if (res.code !== 10000) return
        console.log(res.data.rows)
        const { header, data } = this.formatData(res.data.rows)
        import('@/vendor/Export2Excel').then(excel => {
          excel.export_json_to_excel({
            header: header,
            data: data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
          this.downloadLoading = false
        })
      } catch (error) {
        console.log(error)
      }
    },

    // 删除
    async hDel(id) {
      this.$confirm('你是否要开除此人?').then(
        async() => {
          const res = await delEmployee(id)
          if (res.code !== 10000) return
          this.$message.success(res.message)
          // 删除的特殊情况 当前页码值只有一条数据的时候 让他--
          // 如果只剩下一条数据或者没有数据 就等于1
          if (this.list.length === 1) {
            this.page--
            if (this.page <= 0) {
              this.page = 1
            }
          }
          this.loadEmployeeList()
        }
      ).catch(err => console.log(err))
    },
    // 关闭表单时候触发
    hClose() {
      this.$refs.MySon.resetform()
    },
    // 子传父
    hSuccess() {
      // 子传父亲 成功之后关闭弹层 重新渲染数据
      // 完成之后跳到最大页面
      this.total++
      // 最大的总数 除/ 每页条数  得到最大的页面值
      this.page = Math.ceil(this.total / this.size)
      this.showDialog = false
      this.loadEmployeeList()
    },
    handleSizeChange(val) {
      this.page = 1
      this.size = val
      this.loadEmployeeList()
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.page = val
      this.loadEmployeeList()

      console.log(`当前页: ${val}`)
    },
    // 返回的是 正式还是非正式

    formatEmployment(id) {
      return hireType[id] || '未知'
    },
    // 获取员工列表
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log('getEmployeeList', res)
        this.list = res.data.rows
        this.total = res.data.total
        // 保存数据
      } catch (err) {
        console.log('getEmployeeList', err)
      }
    }
  }
}
</script>
